package models

import (
	"gorm.io/gorm"
	"strings"
)

type Product struct {
	ID          uint64         `gorm:"primaryKey;autoIncrement;comment:商品主键" json:"id"`
	Name        string         `gorm:"type:varchar(255);not null;comment:商品名称" json:"name"`
	Images      string         `gorm:"type:text;comment:商品照片" json:"images" ` // 存 JSON 字符串或逗号分隔 URL
	Description string         `gorm:"type:text;comment:商品描述"  json:"description"`
	Price       float64        `gorm:"type:decimal(10,2);not null;comment:单价（元）" json:"price"` // 建议存“分”，避免浮点误差
	Stock       int            `gorm:"type:int;not null;default:0;comment:库存数量"  json:"stock"`
	Sales       int            `gorm:"type:int;not null;default:0;comment:销量" json:"sales"`
	Status      uint8          `gorm:"type:tinyint;not null;default:1;comment:状态：1-在售，0-下架" json:"status"`
	CreatedAt   JsonTime       `gorm:"column:created_at" json:"created_at"` // 时间格式处理
	UpdatedAt   JsonTime       `gorm:"type:timestamp;comment:更新时间" json:"updated_at"`
	DeletedAt   gorm.DeletedAt `gorm:"type:timestamp;index;comment:删除时间" json:"-"`
	MainImage   string         `gorm:"-" json:"main_image"` // 不映射表，只输出
}

func (Product) TableName() string {
	return "products"
}

func (o *Product) AfterFind(*gorm.DB) error {
	if o.Images == "" {
		o.MainImage = ""
	}
	// 按英文逗号分割并去掉两端空白
	parts := strings.Split(o.Images, ",")
	for _, v := range parts {
		if url := strings.TrimSpace(v); url != "" {
			o.MainImage = url // 返回第一张非空图片
		}
	}
	return nil
}
